package org.example.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.example.dao.DishCategoryMapper;
import org.example.dao.DishUnitMapper;
import org.example.dish.DishTasteFeign;
import org.example.dish_pojo.*;
import org.example.kucun.CaipinFeign;
import org.example.service.IDishInfoService;
import org.example.vo.InfoQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 菜品基础信息表 前端控制器
 * </p>
 *
 * @author mp
 * @since 2025-08-04
 */
@RestController
@RequestMapping("/dish-info")
public class DishInfoController {

    @Autowired
    private IDishInfoService dishInfoService;
    @Autowired
    private DishCategoryMapper dishCategoryMapper;
    @Autowired
    private DishUnitMapper dishUnitMapper;
    @Autowired
    private CaipinFeign caipinFeign;
    @Autowired
    private KucunCaiPinController kucunCaiPinController;



    // 添加菜品
    @RequestMapping("/addDishInfo")
    public Result addDishInfo(@RequestBody DishInfo dishInfo) {
        boolean save = dishInfoService.save(dishInfo);
        if (!save) {
            return new Result(500, "添加失败", null);
        }
        Integer dishId = dishInfo.getDishId();
        Integer categoryId = dishInfo.getCategoryId();
        Integer unitId = dishInfo.getUnitId();
        DishUnit dishUnit = dishUnitMapper.selectById(unitId);
        String uname = dishUnit.getUnitName();
        Inventory inventory = new Inventory();
        inventory.setDishId(dishId);
        inventory.setDishdanwei(uname);
        inventory.setTypeId(categoryId);
        inventory.setDate(new Date());
        inventory.setCurrentStock(100);
        inventory.setHighThreshold(110);
        System.out.println(inventory);
        kucunCaiPinController.addInventory(inventory);
        return new Result(200, "添加成功", null);
    }


    // 删除菜品,调用caipinFeign,实现删除菜品同时删除对应的库存数据
    @RequestMapping("/deleteDishInfo")
    public Result deleteDishInfo(Integer dishId) {
        boolean delete = dishInfoService.removeById(dishId);
        kucunCaiPinController.deleteInventory(dishId);
        if (!delete) {
            return new Result(500, "删除失败", null);
        }
        return new Result(200, "删除成功", null);
    }


    // 批量删除菜品
    @RequestMapping(value = "/deleteDishInfos")
    public Result deleteDishInfos(@RequestBody Integer[] dishIds) {
        boolean delete = dishInfoService.removeByIds(Arrays.asList(dishIds));
        if (!delete) {
            return new Result(500, "删除失败", null);
        }
        return new Result(200, "删除成功", null);
    }


    // 根据id回显数据
    @RequestMapping("/getDishInfoById")
    public Result getDishInfoById(@RequestParam("dishId") Integer dishId) {
        DishInfo dishInfo = dishInfoService.getById(dishId);
        return new Result(200, "操作成功", dishInfo);
    }


    // 修改菜品,调用caipinFeign,实现同时修改对应的库存数据
    @RequestMapping("/updateDishInfo")
    public Result updateDishInfo(@RequestBody DishInfo dishInfo) {
        boolean update = dishInfoService.updateById(dishInfo);
        if (!update) {
            return new Result(500, "修改失败", null);
        }
        Integer unitId = dishInfo.getUnitId();
        DishUnit dishUnit = dishUnitMapper.selectById(unitId);
        Inventory inventory = new Inventory();
        inventory.setDishId(dishInfo.getDishId());
        inventory.setDishdanwei(dishUnit.getUnitName());
        inventory.setTypeId(dishInfo.getCategoryId());
        inventory.setDate(new Date());
        kucunCaiPinController.updateInventory(inventory);
        return new Result(200, "修改成功", null);
    }


    // ... existing code ...
    // 分页查询菜品
    @RequestMapping("/listDishInfo")
    public Result listDishInfo(@RequestBody InfoQuery queryInfo) {
        Page<DishInfo> page = new Page<>(queryInfo.getCurrent(), queryInfo.getSize());
        QueryWrapper<DishInfo> wrapper = new QueryWrapper<>();
        wrapper.like(queryInfo.getDishName() != null, "name", queryInfo.getDishName());
        wrapper.eq(queryInfo.getCategoryId() != null, "category_id", queryInfo.getCategoryId());
        dishInfoService.page(page, wrapper);
        List<DishInfo> list = page.getRecords();
        if (list.size() > 0) {
            for (DishInfo d : list) {
                Integer categoryId = d.getCategoryId();
                Integer unitId = d.getUnitId();
                DishCategory dishCategory = dishCategoryMapper.selectById(categoryId);
                DishUnit dishUnit = dishUnitMapper.selectById(unitId);
//                DishTaste dishTaste = dishTasteFeign.tasteByDishId(d.getDishId());
                d.setCname(dishCategory != null ? dishCategory.getCategoryName() : null);
                d.setUname(dishUnit != null ? dishUnit.getUnitName() : null);
//                d.setTname(dishTaste != null ? dishTaste.getTasteName() : null);
            }
        }
        return new Result(200, "查询成功", page);
    }
// ... existing code ...


    // 批量导入菜品
    @RequestMapping(value = "/importDishInfos", method = RequestMethod.POST)
    public Result importDishInfos(@RequestBody DishInfo[] dishInfos) {
        boolean save = dishInfoService.saveOrUpdateBatch(Arrays.asList(dishInfos));
        if (!save) {
            return new Result(500, "批量导入失败", null);
        }
        return new Result(200, "批量导入成功", null);
    }


    // 批量导出菜品
    @RequestMapping("/exportDishInfos")
    public void exportDishInfos(HttpServletResponse response) throws IOException {
        // 查询数据
        QueryWrapper<DishInfo> wrapper = new QueryWrapper<>();
        wrapper.select("dish_id", "name", "code", "category_id", "unit_id", "base_price", "photo", "is_on_sale");
        List<DishInfo> dishInfos = dishInfoService.list(wrapper);

        // 设置响应头
        response.setContentType("application/octet-stream");
        response.setHeader("Content-Disposition", "attachment;filename=dish_infos.xlsx");

        // 创建Excel文件并写入响应输出流
        generateExcelFile(dishInfos, response.getOutputStream());
    }


    // 生成Excel文件的方法
    private void generateExcelFile(List<DishInfo> dishInfos, OutputStream outputStream) throws IOException {
        // 创建工作簿
        Workbook workbook = new XSSFWorkbook();

        // 创建工作表
        Sheet sheet = workbook.createSheet("菜品信息");

        // 创建表头
        Row headerRow = sheet.createRow(0);
        headerRow.createCell(0).setCellValue("菜品ID");
        headerRow.createCell(1).setCellValue("菜品名称");
        headerRow.createCell(2).setCellValue("菜品编号");
        headerRow.createCell(3).setCellValue("分类ID");
        headerRow.createCell(4).setCellValue("单位ID");
        headerRow.createCell(5).setCellValue("基础价格");
        headerRow.createCell(6).setCellValue("图片");
        headerRow.createCell(7).setCellValue("是否在售");

        // 填充数据
        for (int i = 0; i < dishInfos.size(); i++) {
            DishInfo dishInfo = dishInfos.get(i);
            Row row = sheet.createRow(i + 1);
            row.createCell(0).setCellValue(dishInfo.getDishId());
            row.createCell(1).setCellValue(dishInfo.getName());
            row.createCell(2).setCellValue(dishInfo.getCode());
            row.createCell(3).setCellValue(dishInfo.getCategoryId());
            row.createCell(4).setCellValue(dishInfo.getUnitId());
            row.createCell(5).setCellValue(dishInfo.getBasePrice().doubleValue());
            row.createCell(6).setCellValue(dishInfo.getPhoto());
            row.createCell(7).setCellValue(dishInfo.getIsOnSale() == true ? "是" : "否");
        }

        // 自动调整列宽
        for (int i = 0; i < 8; i++) {
            sheet.autoSizeColumn(i);
        }

        // 写入输出流
        workbook.write(outputStream);

        // 关闭工作簿
        workbook.close();
    }


}

